//
//  NSAttributedString+RichText.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/9.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "NSAttributedString+RichText.h"

@implementation NSAttributedString (RichText)

+ (NSAttributedString *)attributedString:(NSString *)string subString:(NSArray *)subStrings colors:(NSArray *)colors fonts:(NSArray *)fonts {
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSString *subStr in subStrings) {
        [arrM addObject:[NSValue valueWithRange:[string rangeOfString:subStr]]];
    }
    return [self attributedString:string subStringRanage:arrM.copy colors:colors fonts:fonts];
}

+ (NSAttributedString *)attributedString:(NSString *)string subStringRanage:(NSArray <NSValue *>*)subStringRanges colors:(NSArray *)colors fonts:(NSArray *)fonts {
    
    NSMutableAttributedString *attrStrM = [[NSMutableAttributedString alloc] initWithString:string];
    
    for (NSInteger i = 0; i <subStringRanges.count; i++) {
        UIColor *color = nil;
        if (colors.count > i) {
            color = colors[i];
        }else if (colors.count > 0 && colors.count <= i){
            color = colors[0];
        }
        UIFont *font = nil;
        if (fonts.count > i) {
            font = fonts[i];
        }else if (fonts.count > 0 && fonts.count <= i){
            font = fonts[0];
        }
        NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
        if (color) {
            [dictM setObject:color forKey:NSForegroundColorAttributeName];
        }
        if (font) {
            [dictM setObject:font forKey:NSFontAttributeName];
        }
        [attrStrM addAttributes:dictM.copy range:[subStringRanges[i] rangeValue]];
    }
    return attrStrM.copy;
}


+ (NSAttributedString *)attributedString:(NSString *)string subString:(NSArray *)subStrings colors:(NSArray *)colors {
    return [self attributedString:string subString:subStrings colors:colors fonts:nil];
}


@end
